#include <LiquidCrystal.h>


byte data;
unsigned long nilai;
float suhu;
LiquidCrystal lcd = LiquidCrystal(A0,A1,A2,5,4,3,2);
byte newChar[8] = {
	B01100,
	B10010,
	B10010,
	B01100,
	B00000,
	B00000,
	B00000,
	B00000
};

void setup(){

//DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK);
/* Enable SPI, Master, set clock rate fck/16 */
lcd.begin(16,2);
lcd.createChar(0,newChar);

pinMode(10,OUTPUT);//SS
pinMode(11,OUTPUT);//MOSI
pinMode(12,INPUT);//MISO
pinMode(13,OUTPUT);//SCK
pinMode(6,OUTPUT);
analogWrite(6,160);
digitalWrite(7,LOW);//reset optional

SPCR = (1<<SPE)|(1<<MSTR)|(0<<SPR0)|(0<<SPR1);//|(1<<CPOL);//|(1<<CPHA);
data = SPSR;
data = SPDR;
Serial.begin(9600);
//delay(1);
Serial.println("Online");
//digitalWrite(7,HIGH);
//delay(2000);
//init si maksim
//data = DRDY | RS2 | RS1 | RS0 | R/W' | PD | CH1 | Ch0
//setting clock register
data = sendSPI(0x20);//write clock reg
Serial.println(data,HEX);
data = sendSPI(0b10100100);//internal clock,50Hz filter
Serial.println(data,HEX);
//verify clock register
data = sendSPI(0b00101000);//read clock reg
Serial.println(data,HEX);
data = sendSPI(0xF0);
Serial.print("clock reg =");
Serial.println(data,BIN);
//setting setup register
data = sendSPI(0x10);
Serial.println(data,HEX);
data = sendSPI(0b01011110);//start calib+conv,
Serial.println(data,HEX);
Serial.println("Start");


}

void loop(){
  
  do{
  data = sendSPI(0x08);//baca comm register
  data = sendSPI(0x00);
  }
  while(data & (0b10000000));
  data = sendSPI(0x38);
  data = sendSPI(0x00);
  nilai = ((unsigned int) data) << 8;
  data = sendSPI(0x00);
  nilai |= data;
  Serial.print(nilai,DEC);
  //Serial.print(";");
  //Serial.println(nilai,BIN);
  suhu = (nilai * 300ul) / 65535e0;
  Serial.print(';');
  Serial.print(suhu,DEC);
   suhu *= -23.1e-9;
  suhu += 17.58480889e-6;
  suhu = sqrt(suhu);
  suhu += -3.9083e-3;
  suhu /= -1.155e-6;
  Serial.print(';');
  Serial.print(suhu,DEC);
  Serial.println("C");
  delay(200);
  lcd.clear();
  lcd.print("Suhu = ");
  lcd.print(suhu,3);
  lcd.print((char)0);
  lcd.print("C");
  

  
}
void spi_wait() {
  do {} while (!(SPSR & (1 << SPIF)));
}

uint8_t sendSPI(volatile uint8_t fur){
  uint8_t ret;
  SPDR = fur;
  spi_wait();
  ret = SPDR;//clear
   return ret;
}


